# # 导入flask库
# from flask import Flask, render_template
# from markupsafe import escape
#
# app = Flask(__name__)  # 注册运行对象
#
#
# @app.route('/')
# # @app.route('/index')
# @app.route('/home')  # 装饰器为函数绑定对应的 URL：http://127.0.0.1:5000/home
# def index():  # 视图函数（view function）：本质上是获取url地址发送过来的请求
#     name = '周佳伟'  # str
#     movies = [
#         {'title': 'My Neighbor Totoro', 'year': '1988'},
#         {'title': 'Dead Poets Society', 'year': '1989'},
#         {'title': 'A Perfect World', 'year': '1993'},
#         {'title': 'Leon', 'year': '1994'},
#         {'title': 'Mahjong', 'year': '1996'},
#         {'title': 'Swallowtail Butterfly', 'year': '1996'},
#         {'title': 'King of Comedy', 'year': '1999'},
#         {'title': 'Devils on the Doorstep', 'year': '1999'},
#         {'title': 'WALL-E', 'year': '2008'},
#         {'title': 'The Pork of Music', 'year': '2012', },
#     ]
#     return render_template('test.html', name=name, movies=movies)
#
#
# @app.route('/about')
# def hello_about():  # put application's code here
#     return 'Welcome to About Page!'
#
#
# @app.route('/test/<username>')
# # 使用url地址传递动态参数 username，函数需要接受这个参数，不然调用不了
# def test(username):
#     return f'User: {escape(username)}'
#
#
# if __name__ == '__main__':
#     app.run()


# # 导入必要模块（精简到最少）
# from flask import Flask, render_template
# from markupsafe import escape
# from flask_sqlalchemy import SQLAlchemy
# from sqlalchemy import Column, Integer, String, select
# import click
# from pathlib import Path
#
# # ---------------------- 全局唯一DB实例（避免重复初始化） ----------------------
# db = SQLAlchemy()
#
#
# # ---------------------- 数据库模型（使用传统声明式语法，无Mapped） ----------------------
# # 注意：模型类直接继承db.Model，不使用DeclarativeBase（避开映射器冲突）
# class User(db.Model):
#     __tablename__ = 'user'
#     id = Column(Integer, primary_key=True)
#     name = Column(String(20), nullable=False)
#
#
# class Movie(db.Model):
#     __tablename__ = 'movie'
#     id = Column(Integer, primary_key=True)
#     title = Column(String(60), nullable=False)
#     year = Column(String(4), nullable=False)
#
#
# # ---------------------- 应用工厂函数 ----------------------
# def create_app():
#     app = Flask(__name__)
#
#     # 数据库配置（极简版）
#     db_dir = Path(app.root_path) / 'db'
#     db_dir.mkdir(exist_ok=True)
#     db_path = db_dir / 'data.db'
#     app.config['SQLALCHEMY_DATABASE_URI'] = f'sqlite:///{db_path.resolve()}'
#     app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
#
#     # 初始化DB（关键：用db.init_app，而非直接传入app）
#     db.init_app(app)
#
#     # 注册路由
#     @app.route('/')
#     @app.route('/home')
#     def index():
#         with app.app_context():
#             user = db.session.scalar(select(User))
#             movies = db.session.scalars(select(Movie)).all() or []
#         return render_template('index.html', user=user, movies=movies)
#
#     @app.route('/about')
#     def hello_about():
#         return 'Welcome to About Page!'
#
#     @app.route('/test/<username>')
#     def test(username):
#         return f'User: {escape(username)}'
#
#     # 注册自定义命令
#     @app.cli.command('init-db')
#     @click.option('--drop', is_flag=True, help='Drop existing tables first.')
#     def init_db(drop):
#         with app.app_context():
#             if drop:
#                 db.drop_all()
#             db.create_all()
#             click.echo('Database initialized.')
#
#     @app.cli.command('forge')
#     def forge():
#         with app.app_context():
#             db.drop_all()
#             db.create_all()
#             user = User(name='周佳伟')
#             db.session.add(user)
#             movies = [
#                 {'title': 'My Neighbor Totoro', 'year': '1988'},
#                 {'title': 'Dead Poets Society', 'year': '1989'},
#                 {'title': 'A Perfect World', 'year': '1993'},
#                 {'title': 'Leon', 'year': '1994'},
#                 {'title': 'Mahjong', 'year': '1996'},
#                 {'title': 'Swallowtail Butterfly', 'year': '1996'},
#                 {'title': 'King of Comedy', 'year': '1999'},
#                 {'title': 'Devils on the Doorstep', 'year': '1999'},
#                 {'title': 'WALL-E', 'year': '2008'},
#                 {'title': 'The Pork of Music', 'year': '2012'},
#             ]
#             for m in movies:
#                 db.session.add(Movie(title=m['title'], year=m['year']))
#             db.session.commit()
#             click.echo('Test data generated.')
#
#     return app
#
#
# # ---------------------- 运行入口 ----------------------
# if __name__ == '__main__':
#     # 强制关闭重载，确保代码只执行一次
#     app = create_app()
#     app.run(debug=True, use_reloader=False)
# from flask import Flask, render_template
# # 导入Flask-SQLAlchemy扩展：提供ORM功能
# from flask_sqlalchemy import SQLAlchemy
# # 导入click：用于创建Flask自定义命令
# import click
# # 导入路径处理和系统判断模块
# from pathlib import Path
# import sys
#
# # ---------------------- 1.初始化Flask应用 ----------------------
# app = Flask(__name__)
#
# # ---------------------- 2.数据库配置（Flask-SQLAlchemy方式） ----------------------
# SQLITE_PREFIX = 'sqlite:///' if sys.platform.startswith('win') else 'sqlite:////'
# app.config['SQLALCHEMY_DATABASE_URI'] = SQLITE_PREFIX + str(Path(app.root_path) / 'data.db')
# app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
# db = SQLAlchemy(app)
#
# # ---------------------- 3.定义数据库模型（对应数据库表） ----------------------
# class User(db.Model):
#     __tablename__ = 'user'
#     id = db.Column(db.Integer, primary_key=True)
#     name = db.Column(db.String(20))
#
# class Movie(db.Model):
#     __tablename__ = 'movie'
#     id = db.Column(db.Integer, primary_key=True)
#     title = db.Column(db.String(60))
#     year = db.Column(db.String(4))
#
# # ---------------------- 4.自定义命令：初始化数据库，生成测试数据 ----------------------
# @app.cli.command('init-db')
# @click.option('--drop', is_flag=True, help='Delete existing tables before creating new ones.')
# def init_database(drop):
#     if drop:
#         db.drop_all()
#     db.create_all()
#     click.echo('Database initialized successfully!')
#
# @app.cli.command('forge')
# def forge():
#     db.drop_all()
#     db.create_all()
#     test_user = 'Test User'
#     test_movies = [
#         {'title': 'My Neighbor Totoro', 'year': '1988'},
#         {'title': 'Leon', 'year': '1994'},
#         {'title': 'WALL-E', 'year': '2008'},
#         {'title': 'King of Comedy', 'year': '1999'},
#         {'title': 'Dead Poets Society', 'year': '1989'}
#     ]
#     user = User(name=test_user)
#     db.session.add(user)
#     for movie in test_movies:
#         db.session.add(Movie(title=movie['title'], year=movie['year']))
#     db.session.commit()
#     click.echo('Fake test data generated successfully!')
#
# # ---------------------- 5.视图函数：修复 demo 函数，确保返回响应 ----------------------
# # 修复：去掉 {}，添加 return，修正模板路径（根据你的实际目录调整）
# @app.route('/')
# def demo():
#     # 注意：模板路径是相对于 templates 文件夹的
#     # 如果你的模板在 templates/demo/demo.html，路径写 'demo/demo.html'（不用加 ./）
#     return render_template('demo/demo.html')  # 关键：添加 return，修正路径语法
#
# @app.route('/index')
# @app.route('/home')
# def index():
#     user = User.query.first()
#     movies = Movie.query.all()
#     return render_template('index.html', user=user, movies=movies)
#
# # ---------------------- 应用运行入口 ----------------------
# if __name__ == '__main__':
#     app.run(debug=True)
# 导入Flask核心模块：创建应用、渲染模板
from flask import Flask, render_template
from flask_sqlalchemy import SQLAlchemy
import click
from pathlib import Path
import sys

# 1. 初始化Flask应用
app = Flask(__name__)

# 2. 数据库配置
SQLITE_PREFIX = 'sqlite:///' if sys.platform.startswith('win') else 'sqlite:////'
app.config['SQLALCHEMY_DATABASE_URI'] = SQLITE_PREFIX + str(Path(app.root_path) / 'data.db')
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db = SQLAlchemy(app)

# 3. 数据库模型
class User(db.Model):
    __tablename__ = 'user'
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(20))

class Movie(db.Model):
    __tablename__ = 'movie'
    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String(60))
    year = db.Column(db.String(4))

# 4. 自定义命令
@app.cli.command('init-db')
@click.option('--drop', is_flag=True, help='Delete existing tables before creating new ones.')
def init_database(drop):
    if drop:
        db.drop_all()
    db.create_all()
    click.echo('Database initialized successfully!')

@app.cli.command('forge')
def forge():
    db.drop_all()
    db.create_all()
    test_user = 'Test User'
    test_movies = [
        {'title': 'My Neighbor Totoro', 'year': '1988'},
        {'title': 'Leon', 'year': '1994'},
        {'title': 'WALL-E', 'year': '2008'},
        {'title': 'King of Comedy', 'year': '1999'},
        {'title': 'Dead Poets Society', 'year': '1989'}
    ]
    user = User(name=test_user)
    db.session.add(user)
    for movie in test_movies:
        db.session.add(Movie(title=movie['title'], year=movie['year']))
    db.session.commit()
    click.echo('Fake test data generated successfully!')

# 5. 视图函数
@app.route('/')

@app.route('/index')
@app.route('/home')
def index():
    # 可添加数据传递（如需要在主页显示用户/电影）
    user = User.query.first()
    movies = Movie.query.all()
    return render_template('index.html', user=user, movies=movies)

@app.route('/dashboard')
def dashboard():
    return render_template('page/dashboard.html')

@app.route('/users')
def users():
    return render_template('page/users.html')

@app.route('/products')
def products():
    return render_template('page/products.html')

@app.route('/orders')
def orders():
    return render_template('page/orders.html')

# 可选：添加 demo 路由
@app.route('/demo')
def demo():
    return render_template('demo.html')

# 404 错误处理
@app.errorhandler(404)
def page_not_found(error):
    user = User.query.first() or {'name': 'Guest'}
    return render_template('error/404.html', user=user), 404

# 6. 运行入口
if __name__ == '__main__':
    app.run(debug=True, port=1010)  # 新增 port=9090